package cn.ibizlab.businesscentral.core.service.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.businesscentral.core.service.domain.Incident;
import cn.ibizlab.businesscentral.core.service.filter.IncidentSearchContext;
import cn.ibizlab.businesscentral.core.service.service.IIncidentService;

import cn.ibizlab.businesscentral.util.helper.CachedBeanCopier;
import cn.ibizlab.businesscentral.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.businesscentral.core.service.mapper.IncidentMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[案例] 服务对象接口实现
 */
@Slf4j
@Service("IncidentServiceImpl")
public class IncidentServiceImpl extends ServiceImpl<IncidentMapper, Incident> implements IIncidentService {

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IIncidentreSolutionService incidentresolutionService;

    protected cn.ibizlab.businesscentral.core.service.service.IIncidentService incidentService = this;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IKnowledgeArticleIncidentService knowledgearticleincidentService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.ILeadService leadService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IIncidentCustomerService incidentcustomerService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.IContactService contactService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IContractDetailService contractdetailService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IContractService contractService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.IEntitlementService entitlementService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.product.service.IProductService productService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.ISlaKpiInstanceService slakpiinstanceService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.ISlaService slaService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.ISubjectService subjectService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.ITransactionCurrencyService transactioncurrencyService;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.logic.IIncidentActiveLogic activeLogic;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.logic.IIncidentCancelLogic cancelLogic;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.service.service.logic.IIncidentResolveLogic resolveLogic;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(Incident et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy(get(et.getIncidentid()),et);
        return true;
    }

    @Override
    public void createBatch(List<Incident> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(Incident et) {
        fillParentData(et);
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("incidentid",et.getIncidentid())))
            return false;
        CachedBeanCopier.copy(get(et.getIncidentid()),et);
        return true;
    }

    @Override
    public void updateBatch(List<Incident> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result=removeById(key);
        return result ;
    }

    @Override
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public Incident get(String key) {
        Incident et = getById(key);
        if(et==null){
            et=new Incident();
            et.setIncidentid(key);
        }
        else{
        }
        return et;
    }

    @Override
    public Incident getDraft(Incident et) {
        fillParentData(et);
        return et;
    }

    @Override
    @Transactional
    public Incident active(Incident et) {
        activeLogic.execute(et);
         return et ;
    }

    @Override
    @Transactional
    public Incident cancel(Incident et) {
        cancelLogic.execute(et);
         return et ;
    }

    @Override
    public boolean checkKey(Incident et) {
        return (!ObjectUtils.isEmpty(et.getIncidentid()))&&(!Objects.isNull(this.getById(et.getIncidentid())));
    }
    @Override
    @Transactional
    public Incident resolve(Incident et) {
        resolveLogic.execute(et);
         return et ;
    }

    @Override
    @Transactional
    public boolean save(Incident et) {
        if(!saveOrUpdate(et))
            return false;
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(Incident et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? this.update(et) : this.create(et);
        }
    }

    @Override
    public boolean saveBatch(Collection<Incident> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
        return true;
    }

    @Override
    public void saveBatch(List<Incident> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
    }


	@Override
    public List<Incident> selectByCustomerid(String customerid) {
        return baseMapper.selectByCustomerid(customerid);
    }

    @Override
    public void removeByCustomerid(String customerid) {
        this.remove(new QueryWrapper<Incident>().eq("customerid",customerid));
    }

	@Override
    public List<Incident> selectByPrimarycontactid(String contactid) {
        return baseMapper.selectByPrimarycontactid(contactid);
    }

    @Override
    public void removeByPrimarycontactid(String contactid) {
        this.remove(new QueryWrapper<Incident>().eq("primarycontactid",contactid));
    }

	@Override
    public List<Incident> selectByResponsiblecontactid(String contactid) {
        return baseMapper.selectByResponsiblecontactid(contactid);
    }

    @Override
    public void removeByResponsiblecontactid(String contactid) {
        this.remove(new QueryWrapper<Incident>().eq("responsiblecontactid",contactid));
    }

	@Override
    public List<Incident> selectByContractdetailid(String contractdetailid) {
        return baseMapper.selectByContractdetailid(contractdetailid);
    }

    @Override
    public void removeByContractdetailid(String contractdetailid) {
        this.remove(new QueryWrapper<Incident>().eq("contractdetailid",contractdetailid));
    }

	@Override
    public List<Incident> selectByContractid(String contractid) {
        return baseMapper.selectByContractid(contractid);
    }

    @Override
    public void removeByContractid(String contractid) {
        this.remove(new QueryWrapper<Incident>().eq("contractid",contractid));
    }

	@Override
    public List<Incident> selectByEntitlementid(String entitlementid) {
        return baseMapper.selectByEntitlementid(entitlementid);
    }

    @Override
    public void removeByEntitlementid(String entitlementid) {
        this.remove(new QueryWrapper<Incident>().eq("entitlementid",entitlementid));
    }

	@Override
    public List<Incident> selectByExistingcase(String incidentid) {
        return baseMapper.selectByExistingcase(incidentid);
    }

    @Override
    public void removeByExistingcase(String incidentid) {
        this.remove(new QueryWrapper<Incident>().eq("existingcase",incidentid));
    }

	@Override
    public List<Incident> selectByMasterid(String incidentid) {
        return baseMapper.selectByMasterid(incidentid);
    }

    @Override
    public void removeByMasterid(String incidentid) {
        this.remove(new QueryWrapper<Incident>().eq("masterid",incidentid));
    }

	@Override
    public List<Incident> selectByParentcaseid(String incidentid) {
        return baseMapper.selectByParentcaseid(incidentid);
    }

    @Override
    public void removeByParentcaseid(String incidentid) {
        this.remove(new QueryWrapper<Incident>().eq("parentcaseid",incidentid));
    }

	@Override
    public List<Incident> selectByProductid(String productid) {
        return baseMapper.selectByProductid(productid);
    }

    @Override
    public void removeByProductid(String productid) {
        this.remove(new QueryWrapper<Incident>().eq("productid",productid));
    }

	@Override
    public List<Incident> selectByFirstresponsebykpiid(String slakpiinstanceid) {
        return baseMapper.selectByFirstresponsebykpiid(slakpiinstanceid);
    }

    @Override
    public void removeByFirstresponsebykpiid(String slakpiinstanceid) {
        this.remove(new QueryWrapper<Incident>().eq("firstresponsebykpiid",slakpiinstanceid));
    }

	@Override
    public List<Incident> selectByResolvebykpiid(String slakpiinstanceid) {
        return baseMapper.selectByResolvebykpiid(slakpiinstanceid);
    }

    @Override
    public void removeByResolvebykpiid(String slakpiinstanceid) {
        this.remove(new QueryWrapper<Incident>().eq("resolvebykpiid",slakpiinstanceid));
    }

	@Override
    public List<Incident> selectBySlaid(String slaid) {
        return baseMapper.selectBySlaid(slaid);
    }

    @Override
    public void removeBySlaid(String slaid) {
        this.remove(new QueryWrapper<Incident>().eq("slaid",slaid));
    }

	@Override
    public List<Incident> selectBySubjectid(String subjectid) {
        return baseMapper.selectBySubjectid(subjectid);
    }

    @Override
    public void removeBySubjectid(String subjectid) {
        this.remove(new QueryWrapper<Incident>().eq("subjectid",subjectid));
    }

	@Override
    public List<Incident> selectByTransactioncurrencyid(String transactioncurrencyid) {
        return baseMapper.selectByTransactioncurrencyid(transactioncurrencyid);
    }

    @Override
    public void removeByTransactioncurrencyid(String transactioncurrencyid) {
        this.remove(new QueryWrapper<Incident>().eq("transactioncurrencyid",transactioncurrencyid));
    }


    /**
     * 查询集合 ByParentKey
     */
    @Override
    public Page<Incident> searchByParentKey(IncidentSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Incident> pages=baseMapper.searchByParentKey(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Incident>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 已取消
     */
    @Override
    public Page<Incident> searchCancel(IncidentSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Incident> pages=baseMapper.searchCancel(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Incident>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<Incident> searchDefault(IncidentSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Incident> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Incident>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 有效
     */
    @Override
    public Page<Incident> searchEffective(IncidentSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Incident> pages=baseMapper.searchEffective(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Incident>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 已解决
     */
    @Override
    public Page<Incident> searchResolved(IncidentSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Incident> pages=baseMapper.searchResolved(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Incident>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Incident et){
        //实体关系[DER1N_INCIDENT_INCIDENTCUSTOMER_CUSTOMERID]
        if(!ObjectUtils.isEmpty(et.getCustomerid())){
            cn.ibizlab.businesscentral.core.service.domain.IncidentCustomer customer=et.getCustomer();
            if(ObjectUtils.isEmpty(customer)){
                cn.ibizlab.businesscentral.core.service.domain.IncidentCustomer majorEntity=incidentcustomerService.get(et.getCustomerid());
                et.setCustomer(majorEntity);
                customer=majorEntity;
            }
            et.setCustomername(customer.getCustomername());
            et.setCustomertype(customer.getCustomertype());
        }
        //实体关系[DER1N_INCIDENT__CONTACT__PRIMARYCONTACTID]
        if(!ObjectUtils.isEmpty(et.getPrimarycontactid())){
            cn.ibizlab.businesscentral.core.base.domain.Contact primarycontact=et.getPrimarycontact();
            if(ObjectUtils.isEmpty(primarycontact)){
                cn.ibizlab.businesscentral.core.base.domain.Contact majorEntity=contactService.get(et.getPrimarycontactid());
                et.setPrimarycontact(majorEntity);
                primarycontact=majorEntity;
            }
            et.setPrimarycontactname(primarycontact.getFullname());
        }
        //实体关系[DER1N_INCIDENT__CONTACT__RESPONSIBLECONTACTID]
        if(!ObjectUtils.isEmpty(et.getResponsiblecontactid())){
            cn.ibizlab.businesscentral.core.base.domain.Contact responsiblecontact=et.getResponsiblecontact();
            if(ObjectUtils.isEmpty(responsiblecontact)){
                cn.ibizlab.businesscentral.core.base.domain.Contact majorEntity=contactService.get(et.getResponsiblecontactid());
                et.setResponsiblecontact(majorEntity);
                responsiblecontact=majorEntity;
            }
            et.setResponsiblecontactname(responsiblecontact.getFullname());
        }
        //实体关系[DER1N_INCIDENT__CONTRACTDETAIL__CONTRACTDETAILID]
        if(!ObjectUtils.isEmpty(et.getContractdetailid())){
            cn.ibizlab.businesscentral.core.service.domain.ContractDetail contractdetail=et.getContractdetail();
            if(ObjectUtils.isEmpty(contractdetail)){
                cn.ibizlab.businesscentral.core.service.domain.ContractDetail majorEntity=contractdetailService.get(et.getContractdetailid());
                et.setContractdetail(majorEntity);
                contractdetail=majorEntity;
            }
            et.setContractdetailname(contractdetail.getTitle());
        }
        //实体关系[DER1N_INCIDENT__CONTRACT__CONTRACTID]
        if(!ObjectUtils.isEmpty(et.getContractid())){
            cn.ibizlab.businesscentral.core.service.domain.Contract contract=et.getContract();
            if(ObjectUtils.isEmpty(contract)){
                cn.ibizlab.businesscentral.core.service.domain.Contract majorEntity=contractService.get(et.getContractid());
                et.setContract(majorEntity);
                contract=majorEntity;
            }
            et.setContractname(contract.getTitle());
        }
        //实体关系[DER1N_INCIDENT__ENTITLEMENT__ENTITLEMENTID]
        if(!ObjectUtils.isEmpty(et.getEntitlementid())){
            cn.ibizlab.businesscentral.core.service.domain.Entitlement entitlement=et.getEntitlement();
            if(ObjectUtils.isEmpty(entitlement)){
                cn.ibizlab.businesscentral.core.service.domain.Entitlement majorEntity=entitlementService.get(et.getEntitlementid());
                et.setEntitlement(majorEntity);
                entitlement=majorEntity;
            }
            et.setEntitlementname(entitlement.getEntitlementname());
        }
        //实体关系[DER1N_INCIDENT__INCIDENT__EXISTINGCASE]
        if(!ObjectUtils.isEmpty(et.getExistingcase())){
            cn.ibizlab.businesscentral.core.service.domain.Incident existingca=et.getExistingca();
            if(ObjectUtils.isEmpty(existingca)){
                cn.ibizlab.businesscentral.core.service.domain.Incident majorEntity=incidentService.get(et.getExistingcase());
                et.setExistingca(majorEntity);
                existingca=majorEntity;
            }
            et.setExistingcasename(existingca.getTitle());
        }
        //实体关系[DER1N_INCIDENT__INCIDENT__MASTERID]
        if(!ObjectUtils.isEmpty(et.getMasterid())){
            cn.ibizlab.businesscentral.core.service.domain.Incident master=et.getMaster();
            if(ObjectUtils.isEmpty(master)){
                cn.ibizlab.businesscentral.core.service.domain.Incident majorEntity=incidentService.get(et.getMasterid());
                et.setMaster(majorEntity);
                master=majorEntity;
            }
            et.setMastername(master.getTitle());
        }
        //实体关系[DER1N_INCIDENT__INCIDENT__PARENTCASEID]
        if(!ObjectUtils.isEmpty(et.getParentcaseid())){
            cn.ibizlab.businesscentral.core.service.domain.Incident parentcase=et.getParentcase();
            if(ObjectUtils.isEmpty(parentcase)){
                cn.ibizlab.businesscentral.core.service.domain.Incident majorEntity=incidentService.get(et.getParentcaseid());
                et.setParentcase(majorEntity);
                parentcase=majorEntity;
            }
            et.setParentcasename(parentcase.getTitle());
        }
        //实体关系[DER1N_INCIDENT__PRODUCT__PRODUCTID]
        if(!ObjectUtils.isEmpty(et.getProductid())){
            cn.ibizlab.businesscentral.core.product.domain.Product product=et.getProduct();
            if(ObjectUtils.isEmpty(product)){
                cn.ibizlab.businesscentral.core.product.domain.Product majorEntity=productService.get(et.getProductid());
                et.setProduct(majorEntity);
                product=majorEntity;
            }
            et.setProductname(product.getProductname());
        }
        //实体关系[DER1N_INCIDENT__SLAKPIINSTANCE__FIRSTRESPONSEBYKPIID]
        if(!ObjectUtils.isEmpty(et.getFirstresponsebykpiid())){
            cn.ibizlab.businesscentral.core.base.domain.SlaKpiInstance firstresponsebykpi=et.getFirstresponsebykpi();
            if(ObjectUtils.isEmpty(firstresponsebykpi)){
                cn.ibizlab.businesscentral.core.base.domain.SlaKpiInstance majorEntity=slakpiinstanceService.get(et.getFirstresponsebykpiid());
                et.setFirstresponsebykpi(majorEntity);
                firstresponsebykpi=majorEntity;
            }
            et.setFirstresponsebykpiname(firstresponsebykpi.getSlakpiinstancename());
        }
        //实体关系[DER1N_INCIDENT__SLAKPIINSTANCE__RESOLVEBYKPIID]
        if(!ObjectUtils.isEmpty(et.getResolvebykpiid())){
            cn.ibizlab.businesscentral.core.base.domain.SlaKpiInstance resolvebykpi=et.getResolvebykpi();
            if(ObjectUtils.isEmpty(resolvebykpi)){
                cn.ibizlab.businesscentral.core.base.domain.SlaKpiInstance majorEntity=slakpiinstanceService.get(et.getResolvebykpiid());
                et.setResolvebykpi(majorEntity);
                resolvebykpi=majorEntity;
            }
            et.setResolvebykpiname(resolvebykpi.getSlakpiinstancename());
        }
        //实体关系[DER1N_INCIDENT__SLA__SLAID]
        if(!ObjectUtils.isEmpty(et.getSlaid())){
            cn.ibizlab.businesscentral.core.base.domain.Sla sla=et.getSla();
            if(ObjectUtils.isEmpty(sla)){
                cn.ibizlab.businesscentral.core.base.domain.Sla majorEntity=slaService.get(et.getSlaid());
                et.setSla(majorEntity);
                sla=majorEntity;
            }
            et.setSlaname(sla.getSlaname());
        }
        //实体关系[DER1N_INCIDENT__SUBJECT__SUBJECTID]
        if(!ObjectUtils.isEmpty(et.getSubjectid())){
            cn.ibizlab.businesscentral.core.base.domain.Subject subject=et.getSubject();
            if(ObjectUtils.isEmpty(subject)){
                cn.ibizlab.businesscentral.core.base.domain.Subject majorEntity=subjectService.get(et.getSubjectid());
                et.setSubject(majorEntity);
                subject=majorEntity;
            }
            et.setSubjectname(subject.getTitle());
        }
        //实体关系[DER1N_INCIDENT__TRANSACTIONCURRENCY__TRANSACTIONCURRENCYID]
        if(!ObjectUtils.isEmpty(et.getTransactioncurrencyid())){
            cn.ibizlab.businesscentral.core.base.domain.TransactionCurrency transactioncurrency=et.getTransactioncurrency();
            if(ObjectUtils.isEmpty(transactioncurrency)){
                cn.ibizlab.businesscentral.core.base.domain.TransactionCurrency majorEntity=transactioncurrencyService.get(et.getTransactioncurrencyid());
                et.setTransactioncurrency(majorEntity);
                transactioncurrency=majorEntity;
            }
            et.setCurrencyname(transactioncurrency.getCurrencyname());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<Incident> getIncidentByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<Incident> getIncidentByEntities(List<Incident> entities) {
        List ids =new ArrayList();
        for(Incident entity : entities){
            Serializable id=entity.getIncidentid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0)
           return this.listByIds(ids);
        else
           return entities;
    }

}



